<template>
  <view class="_p5 _flex-y _wrapper">
    <table-query
      :queryParams="queryParams"
      @search="loadData"
      @add="syncData()"
      ref="refTableQuery"
    ></table-query>
    <div class="_wrapper _flex-item-1 _box-scroll _over-scroll-hidden">
      <el-table
        :data="dataList"
        height="100%"
        border
        style="width: 100%"
        :highlight-current-row="true"
        stripe
        row-key="id"
        size="small"
        :tooltip-options="{}"
      >
        <template v-for="(meta, _index) in fields" :key="_index">
          <el-table-column
            :prop="meta.name"
            :label="meta.memo || meta.name"
            :show-overflow-tooltip="true"
            sortable="custom"
            align="center"
          >
            <template #default="scope">
              <template v-if="meta.dictList || meta.dictListFun">
                <com-dict-show
                  :dictList="meta.dictList"
                  :dictVal="scope.row[meta.name]"
                  :dictFun="meta.dictListFun"
                />
              </template>
              <template v-else-if="meta.component">
                <plugin-pack
                  :component="meta.component"
                  :component-param="scope.row"
                ></plugin-pack>
              </template>
              <template v-else-if="meta.type === 3">
                {{
                  scope.row[meta.name] && $dayjs(scope.row[meta.name]).format()
                }}
              </template>
              <template v-else-if="meta.type === 140">
                <com-tags-select
                  :disable="true"
                  v-model:checks="scope.row[meta.name]"
                />
              </template>
              <template v-else-if="meta.type === 150">
                <com-param-select
                  v-model:defaultIds="scope.row[meta.name]"
                ></com-param-select>
              </template>
              <template v-else-if="meta.type === 180">
                <plugin-pack>
                  <template v-slot:content>
                    <big-text v-model="scope.row[meta.name]"></big-text>
                  </template>
                </plugin-pack>
              </template>
              <template v-else-if="[110, 111].includes(meta.type)">
                <com-img v-model:value="scope.row[meta.name]" />
              </template>
              <template v-else>
                <el-button
                  v-if="scope.row[meta.name]"
                  v-copyClipboard="scope.row[meta.name]"
                  size="small"
                  >{{ scope.row[meta.name] }}</el-button
                >
              </template>
            </template>
          </el-table-column>
        </template>
        <el-table-column fixed="right" label="操作" width="120" align="center">
          <template #default="scope">
            <view class="uni-group">
              <el-button
                circle
                type="info"
                size="small"
                @click="syncData(scope.row)"
              >
                <el-icon><EditPen /></el-icon>
              </el-button>
              <el-popconfirm
                title="确认删除该条记录?"
                @confirm="remove(scope.row)"
              >
                <template #reference>
                  <el-button type="danger" size="small" circle>
                    <el-icon><Delete /></el-icon>
                  </el-button>
                </template>
              </el-popconfirm>
            </view>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <ComPage ref="ComPage" :total="dataTotal" @load="loadData()"></ComPage>
    <el-drawer size="80%" v-model="formDialogVisible" title="数据更新">
      <ComUpdate
        v-if="currentForm"
        :dataCode="code"
        :dataId="currentForm.id"
        :fixParam="fixParam"
        @close="syncClose()"
      ></ComUpdate>
    </el-drawer>
  </view>
</template>

<script>
import ToolAction from "@/tool/http/tool-action.js";
import extension from "./extension.js";
import ComPage from "@/components/com-page/com-page.vue";
import ComTagsSelect from "@/components/com-tags-select/com-tags-select.vue";
import ComParamSelect from "@/components/com-param-select/com-param-select.vue";
import ComImg from "@/components/com-img/com-img.vue";
import ComUpdate from "./components/update/data-form.vue";
import ComDictShow from "@/components/com-dict/com-dict-show.vue";
import pluginPack from "./components/plugin-pack/plugin-pack.vue";
import TableQuery from "./components/table-query/table-query.vue";
import BigText from "./components/big-text/big-text.vue";

let api;

export default {
  components: {
    ComPage,
    ComTagsSelect,
    ComParamSelect,
    ComImg,
    ComUpdate,
    ComDictShow,
    pluginPack,
    TableQuery,
    BigText,
  },
  props: {
    tableCode: {
      type: String,
      default: "",
    },
    fixParam: {
      type: Object,
      default: () => {},
    },
  },
  data() {
    return {
      ruleConfig: {
        baseField: [],
        metadata: [],
      },
      tempMetadata: [],
      dataList: [],
      dataTotal: 0,
      selectedIndexs: [],
      code: this.tableCode || this.$route.query.code,
      formDialogVisible: false,
      currentForm: undefined,
    };
  },
  computed: {
    queryParams() {
      return [
        ...this.meta
          .filter((item) => item && item.dictList && item.dictList.length > 0)
          .map((item) => ({
            name: item.name,
            type: "eq",
            dictList: item.dictList,
          })),
        ...(this.ruleConfig.queryParams || []),
      ];
    },
    fields() {
      return [
        ...this.ruleConfig.baseField,
        ...this.meta,
        ...this.tempMetadata,
      ].filter((item) => !Object.keys(this.fixParam || {}).includes(item.name));
    },
    meta() {
      return this.ruleConfig.metadata.filter((_item) => !_item.hidden);
    },
  },
  async mounted() {
    api = ToolAction.init(this.code);
    await this.loadMetaData();
    this.loadData();
    this.$tool.onEvent("commonLoadData-" + this.code, () => {
      if (this.$refs.ComPage) {
        this.$refs.ComPage.reset();
        this.loadData();
      }
    });
  },
  methods: {
    syncClose() {
      this.formDialogVisible = false;
      this.loadData();
    },
    syncData(row = {}) {
      this.currentForm = undefined;
      this.$nextTick(() => {
        this.currentForm = row;
        this.formDialogVisible = true;
      });
    },
    async loadMetaData() {
      this.ruleConfig = await extension.init(this.code);
    },
    loadData() {
      (this.ruleConfig.listData || api.page)({
        page: this.$refs.ComPage.pageInfo(),
        rules: this.buildRules(),
      }).then(async (res) => {
        let records = res.records || res;
        // 初始化列表扩展字段 - 根据数据扩展
        if (this.ruleConfig.listFieldExtend) {
          this.ruleConfig.listFieldExtend(records).then((res) => {
            if (res) {
              this.tempMetadata = res.metadata;
              this.dataList = [...res.records];
            }
          });
        }
        this.dataList = records;
        this.dataTotal = res.total || records.length;
      });
    },
    /**
     * 构建查询条件 - rules
     */
    buildRules() {
      // 构建页面选择条件
      let rules = this.$refs.refTableQuery.rules();
      // 封装固定传入条件
      if (this.fixParam) {
        Object.keys(this.fixParam).forEach((key) => {
          rules[`${key}__eq`] = this.fixParam[key];
        });
      }
      return this.$tool.objClear(rules);
    },
    remove(item) {
      api.remove(item).then(() => {
        this.loadData();
      });
    },
    removeAll() {},
    selectionChange(e) {
      this.selectedIndexs = e.detail.index;
    },
    sortChange(e, name) {
      this.orderByFieldName = name;
      if (e.order) {
        // this.orderby = name + " " + orderByMapping[e.order];
      } else {
        this.orderby = "";
      }
      this.$refs.table.clearSelection();
      this.$nextTick(() => {
        this.$refs.udb.loadData();
      });
    },
  },
};
</script>

<style></style>
